package ch.fhnw.qualiscan.application.pages.tabs;

import java.util.Iterator;
import java.util.List;

import ch.fhnw.qualiscan.Config;
import ch.fhnw.qualiscan.application.modals.AddParticipantToSurvey;
import ch.fhnw.qualiscan.application.modals.DeleteParticipantFromSurvey;
import ch.fhnw.qualiscan.application.pages.EditSurvey;
import ch.fhnw.qualiscan.core.db.helpers.participantsTableArgs;
import ch.fhnw.qualiscan.core.db.pojos.Domain;
import ch.fhnw.qualiscan.core.db.pojos.Question;
import ch.fhnw.qualiscan.core.db.pojos.SurveyUserRole;
import ch.fhnw.qualiscan.core.helpers.EmailHelper;
import ch.fhnw.qualiscan.core.libraries.NotificationLib;

import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Component;
import com.vaadin.ui.ProgressIndicator;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalLayout;

import eu.livotov.tpt.TPTApplication;
import eu.livotov.tpt.gui.dialogs.OptionDialog;
import eu.livotov.tpt.gui.dialogs.OptionDialog.OptionDialogResultListener;
import eu.livotov.tpt.gui.dialogs.OptionKind;
import eu.livotov.tpt.i18n.TM;

/**
 * This shows a table of all participants of a survey.
 */
@SuppressWarnings("serial")
public class EditSurveyTab2Coordinator extends VerticalLayout {
	
	public EditSurvey editSurvey;
	public Table participantsTable;
	public BeanItemContainer<participantsTableArgs> tableContainer;
	
	public EditSurveyTab2Coordinator(EditSurvey editSurvey) {
		this.editSurvey = editSurvey;
		
		tableContainer = new BeanItemContainer<participantsTableArgs>(participantsTableArgs.class);
		List<SurveyUserRole> surList = editSurvey.surveyModel.getSurListForSurvey(editSurvey.currentSurvey);
		for(int i = 0; i < surList.size(); i++) {
			if (surList.get(i).getUser().getId() == editSurvey.userSession.getId() && surList.get(i).getRole().getId() == Config.COORDINATOR_ID) {}
			else {
				String role = editSurvey.userModel.getRoleText(surList.get(i).getRole(), editSurvey.userSession.getLanguage()).getTitle();
				participantsTableArgs pta = new participantsTableArgs(surList.get(i), surList.get(i).getUser().getFirstname(), surList.get(i).getUser().getLastname(),surList.get(i).getUser().getEmail(), role);
				tableContainer.addBean(pta);
			}
		}
		
		buildLayout();
	}
	
	public void buildLayout() {
		Button newParticipant = new Button(TM.get("action.add"), new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				editSurvey.openModal(new AddParticipantToSurvey(editSurvey.currentSurvey, (EditSurveyTab2Coordinator) event.getButton().getData()));
			}
		});
		newParticipant.setIcon(Config.ICON_ADDUSER);
		newParticipant.setData(this);
		
		participantsTable = new Table();
		participantsTable.setWidth("100%");
		participantsTable.setPageLength(0);
		participantsTable.setSelectable(false);
		
		participantsTable.addGeneratedColumn("participantProgress", new Table.ColumnGenerator() {
			public Component generateCell(Table source, Object itemId, Object columnId) {
				SurveyUserRole sur = (SurveyUserRole) source.getContainerProperty(itemId, "sur").getValue();
				
				// no progress bar for experts
				if(sur.getRole().getId() == Config.EXPERT_ID) {
					return null;
				}
				
				Iterator<Domain> itd = sur.getSurvey().getDomains().iterator();
				int nQuestions = 0;
				int totalAnswers = 0;
				
				while(itd.hasNext()) {
					Domain d = itd.next();
					Iterator<Question> questionIterator= d.getQuestions().iterator();
					while (questionIterator.hasNext()) {
						Question q = questionIterator.next();
						if (q.getSubquestions().size() > 0) {
							nQuestions = nQuestions + q.getSubquestions().size();
						}
						else {
							nQuestions++;
						}

					}
					totalAnswers = totalAnswers + editSurvey.domainModel.getNumberOfAnswersForSurAndDomain(sur, d);
				}
				
				float progress = (float)totalAnswers/(float)nQuestions;
				ProgressIndicator pi = new ProgressIndicator(progress);
				pi.setPollingInterval(180000);
				
				return pi;
			}
		});
		
		participantsTable.addGeneratedColumn("participantDeleteButton", new Table.ColumnGenerator() {
			public Component generateCell(Table source, Object itemId, Object columnId) {
				Object[] buttonData = new Object[2];
				buttonData[0] = itemId;
				buttonData[1] = source;
 				Button deleteButton = new Button(TM.get("action.delete"), new Button.ClickListener() {
					public void buttonClick(ClickEvent event) {
						Object[] buttonData = (Object[]) event.getButton().getData();
						participantsTableArgs pta = (participantsTableArgs) buttonData[0];
						Table source = (Table) buttonData[1];
						BeanItemContainer<participantsTableArgs> tableContainer = (BeanItemContainer<participantsTableArgs>) source.getContainerDataSource();
						editSurvey.openModal(new DeleteParticipantFromSurvey(pta, tableContainer));
					}
				});
 				deleteButton.setIcon(Config.ICON_DELETE);
 				deleteButton.setData(buttonData);
				
				return deleteButton;
			}
		});
		
		participantsTable.addGeneratedColumn("participantReminderButton", new Table.ColumnGenerator() {
			public Component generateCell(Table source, final Object itemId, Object columnId) {
				Button reminderButton = new Button(TM.get("action.remind"));
				reminderButton.setData(itemId);
				reminderButton.addListener(new Button.ClickListener() {
					public void buttonClick(final ClickEvent event) {
						final OptionDialog dlg = new OptionDialog (TPTApplication.getCurrentApplication());
						
						// get name or email
						participantsTableArgs object = (participantsTableArgs) itemId;
						String recipient;
						if(object.getFirstname().equals(""))
							recipient = object.getEmail();
						else 
							recipient = object.getFirstname() + " " + object.getLastname();
						
	                    dlg.showConfirmationDialog(TM.get("email.reminder"), TM.get("email.remind", recipient), new OptionDialogResultListener() {
                            public void dialogClosed(OptionKind arg0) {
                                if(arg0 == OptionKind.OK) {
                            		participantsTableArgs pta = (participantsTableArgs) event.getButton().getData();
                            		
                            		EmailHelper eh = new EmailHelper();
                            		EditSurveyTab2Coordinator est = (EditSurveyTab2Coordinator) event.getButton().getParent().getParent().getParent();
                            		String Coordinator = est.editSurvey.userSession.getFirstname() + " " + est.editSurvey.userSession.getLastname();
                            		//User hasn't logged in so far. Send Invitation Mail again.

                            		if(pta.getFirstname().equals("")) {
                            			eh.sendInvitationMail(pta.getSur(), TM.get("email.reminder.invitationtext"));
                            		}
                            		else {
                            			eh.sendEmail(pta.getEmail(), TM.get("email.reminder.subject", est.editSurvey.currentSurvey.getTitle()), TM.get("email.remindertext", pta.getFirstname() + " " + pta.getLastname(), Coordinator, est.editSurvey.currentSurvey.getTitle(), Config.BASE_URL));
                            		}
                            		
                            		
                            		NotificationLib.showSuccess(TM.get("action.sent"), TM.get("email.reminder.sent"));
                                }
                            }
	                    });
					}
				});
				reminderButton.setIcon(Config.ICON_USER_COMMENT);
				return reminderButton;
			}
		});
		
		participantsTable.setContainerDataSource(tableContainer);
		
		participantsTable.setColumnHeader("firstname", TM.get("editsurvey.participantstable.firstname"));
		participantsTable.setColumnHeader("lastname", TM.get("editsurvey.participantstable.lastname"));
		participantsTable.setColumnHeader("email", TM.get("editsurvey.participantstable.email"));
		participantsTable.setColumnHeader("role", TM.get("editsurvey.participantstable.role"));
		participantsTable.setColumnHeader("participantProgress", TM.get("editsurvey.participantstable.progress"));
		participantsTable.setColumnHeader("participantDeleteButton", TM.get("action.delete"));
		participantsTable.setColumnHeader("participantReminderButton", TM.get("action.remind"));
		
		participantsTable.setVisibleColumns(new Object[]{"firstname", "lastname", "email", "role", "participantProgress", "participantDeleteButton", "participantReminderButton"});
		
		VerticalLayout participantsWrapper = new VerticalLayout();
		participantsWrapper.setSpacing(true);
		participantsWrapper.setMargin(true);
		participantsWrapper.addComponent(editSurvey.textHelper.h3(TM.get("editsurvey.tab2.title")));
		participantsWrapper.addComponent(newParticipant);
		participantsWrapper.addComponent(participantsTable);
		
		addComponent(participantsWrapper);
	}

}
